/**
 * v-copy
 * 复制某个值至剪贴板
 * 接收参数：string类型/Ref<string>类型/Reactive<string>类型
 */
import type {Directive, DirectiveBinding} from 'vue'
import {ElMessage}                        from 'element-plus'

interface ElType extends HTMLElement {
    copyData: string | number,
    __handleClick__: any
}

const directive: Directive = {
    mounted(el: ElType, binding: DirectiveBinding) {
        el.setAttribute("style", "cursor: pointer;background-image: linear-gradient(to bottom, #877e6d, #2ed7ae); -webkit-background-clip: text;  ")
        el.copyData = binding.value
        el.addEventListener('click', handleClick)
    },
    updated(el: ElType, binding: DirectiveBinding) {
        el.copyData = binding.value
    },
    beforeUnmount(el: ElType) {
        el.removeEventListener('click', el.__handleClick__)
    }
}

function handleClick(this: ElType, ev: MouseEvent) {
    let input   = document.createElement('input')
    input.value = this.copyData.toLocaleString()
    document.body.appendChild(input)
    input.select()
    document.execCommand('Copy')
    document.body.removeChild(input)
    ElMessage({
        type   : 'success',
        message: '复制成功'
    })
}

export default directive
